﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model.OrderSingleton;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Model.ViewModel;
using DeHeng_Mes.Utils;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DeHeng_Mes.PlcService
{
    public class EntranceService
    {
        #region 成员实例
        OrderDao orderDao = new OrderDao();
        #endregion

        /// <summary>
        /// 工位入站
        /// </summary>
        /// <param name="station"></param>
        /// <returns></returns>
        public (int, List<int>) StationEntrance(string station, List<string> codes, string operation)
        {
            // 初始化报警码
            List<int> errorCodes = new List<int>();

            // 初始化NG状态列表
            List<bool> NgStatus = new List<bool>();

            // 获取入站时间
            DateTime now = DateTime.Now;

            int count = 0;

            try
            {
                foreach (var code in codes)
                {
                    if (station.Equals(SystemConstant.NgStationL) || station.Equals(SystemConstant.NgStationR))
                    {
                        // 记录NG工位入站
                        orderDao.NgStationSave(new NgStation()
                        {
                            CreateTime = now,
                            Station = station,
                            TraceId = code,
                            Status = "2"
                        });
                    }
                    else
                    {
                        bool isSave = orderDao.InsertStationStartTime(code, station, now, operation);

                        if (isSave)
                            Tools.ProduceLogText($"[{station}]触发入站存储，入站时间[{now}]，追溯码[{code}]");
                    }

                    count++;
                }
            }
            catch (Exception ex)
            {
                errorCodes.Add(1505);

                Tools.ProduceLogTextError($"[{station}]触发入站失败，原因是[{ex.Message}]");

                return (-1, errorCodes);
            }

            if (NgStatus.Count > 0) return (2, errorCodes);

            else return (1, errorCodes);
        }
    }
}
